﻿
$(function () {
    window.gp = {}; //全局对象
    window.gp.browser = {};
    window.gp.cache = {};   //本地缓存
    window.gp.cache.isLocalStorage = true;
    initCache();
    window.gp.user = {
        Current: function () {
            if (typeof (gp.cache.get("jyzf_loacl_user")) != "undefined")
                return JSON.parse(gp.cache.get("jyzf_loacl_user"));
            else return null;
        },
        Set: function (user) {
            user
            gp.cache.set("jyzf_loacl_user", user)
        },
        Remove: function () {
            gp.cache.remove("jyzf_loacl_user");
        }
    }

    $("#btnLogout").click(function () {
        AjaxPost("/Admin/Account/LogOff", null, function (result) {
            if (result.code == 200) {
                window.gp.user.Remove();
                window.location = "/";
            }
        });
    });
});


function initCache() {
    //设置本地缓存
    gp.cache.set = function (name, value) {
        if (typeof value != "string") {
            value = JSON.stringify(value);
        }
        if (gp.cache.isLocalStorage) {
            localStorage[name] = value;
        }
    };
    //读取本地缓存
    gp.cache.get = function (name) {
        if (gp.cache.isLocalStorage) {
            return localStorage[name];
        }
    };
    //清除本地指定缓存
    gp.cache.remove = function (name) {
        if (gp.cache.isLocalStorage) {
            localStorage.removeItem(name);
        }
    };
};
/*
* jQuery Ajax调用封装
* url:			调用地址
* data:			可选参数,表示Ajax调用参数
* onSuccess:	可选参数,成功回调函数,函数签名为  function(data), data参数为调用结果
* modal:		可选参数,是否作为模态对话框显示，默认为true
* isAlert:		可选参数,提示错误信息，默认为true
* async:		可选参数,是否异步调用，默认为true
* onError:		可选参数,失败回调函数,函数签名为  function (XMLHttpRequest, textStatus, errorThrown)
* onComplete:	可选参数,Ajax调用完成回调函数,函数签名为  function (XMLHttpRequest, textStatus)
* dataType:		可选参数,Ajax返回数据类型,默认为 "text"
*/
AjaxPost = function (url, data, onSuccess, onError, onComplete, async, dataType) {
    var ajaxHandler = $.ajax.call(this, {
        type: "post",
        url: url,
        timeout: 12000,
        cache: false,
        contentType: "application/json",
        dataType: (dataType ? dataType : "text"),
        data: data,
        async: (async == false ? async : true),
        success: function (json) {
            var result = JSON.parse(json || null);
            try {
                result.data = JSON.parse(result.data || null);
            } catch (e) {
            }
            if (result.code != 200) {
                alert(result.msg, "error");
                if (typeof (onError) == "function")
                    onError.call();
            } else {
                if (typeof (onSuccess) == "function")
                    onSuccess.call(this, result);
            }

        },
        error: function (e, status) { //错误时执行
            if (status == 'error' && e.readyState === 0) { //超时,status还有success,error等值的情况
                if (typeof (onError) == "function")
                    onError.call();
            }
        },
        complete: function (e, status) { //请求完成后最终执行参数
            if (status == 'timeout') { //超时,status还有success,error等值的情况
                alert("访问超时");
                ajaxHandler.abort();
                if (typeof (onError) == "function")
                    onError.call();
            }
            if (typeof (onComplete) == "function")
                onComplete.call();
        }
    });
    return ajaxHandler;
};

/*
* 重写 window.alert
* msg:			提示消息
* type:			可选参数,默认为info（success,info,error,warning）
* position:	    可选参数,默认为center（eg. top-end）
*/
window.alert = function (msg, type = "info", position = "center") {
    var Toast;
    if (typeof (Toast) == "undefined") {
        Toast = Swal.mixin({
            toast: true,
            position: position,
            showConfirmButton: false,
            timer: 1000
        });
    }
    Toast.fire({ type: type, title: msg });
};
/*
* 重写 window.confirm
* msg:			提示消息
* onConfirm     可选参数,确认之后执行函数
* title:	    可选参数,标题
*/
window.confirm = function (msg, onConfirm, title = "提示") {
    var dlgConfirm = $("#modal-default-confirm");
    if (title == "警告") {
        $("#modal-confirm-title", dlgConfirm).html("<span style='color:red'>" + title + "</span>");
    }
    else {
        $("#modal-confirm-title", dlgConfirm).text(title);
    }
    $("#modal-confirm-message", dlgConfirm).html(msg);
    $("#modal-confirm-button-confirm").click(function () {
        if (typeof (onConfirm) == "function") {
            onConfirm.call();
        }
        dlgConfirm.modal("hide");
    });
    dlgConfirm.modal();
};

window.showloading = function () {
    var dlgLoading = $("#modal-default-overlay");
    dlgLoading.modal();
}

window.hideloading = function () {
    var dlgLoading = $("#modal-default-overlay");
    dlgLoading.modal("hide");
}



$.tools = {
    //格式化JSON格式日期
    formatJsonDate: function (jsondate, format) {
        var datetime = "";
        if (!jsondate) {
            return "";
        }
        jsondate = jsondate + "";
        if (/^\/Date[(].+[)]\/$/.test(jsondate)) {
            jsondate = jsondate.replace("/Date(", "").replace(")/", "");
            if (jsondate.indexOf("+") > -1) {
                jsondate = jsondate.substring(0, jsondate.indexOf("+"));
            }
            else if (jsondate.indexOf("-") > -1) {
                jsondate = jsondate.substring(0, jsondate.indexOf("-"));
            }
            datetime = new Date(parseInt(jsondate, 10));
        } else {
            var tail = "";
            if (jsondate.endsWith("+08:00")) {
                jsondate = jsondate.substring(0, jsondate.indexOf("+08:00"));
                tail = "+08:00";
            }
            else if (jsondate.endsWith("Z")) {
                jsondate = jsondate.substring(0, jsondate.indexOf("Z"));
                tail = "Z";
            }
            //常规时间
            //如果不存在毫秒
            if (jsondate.indexOf(".") < 0) {
                jsondate += ".0";
            }
            jsondate = jsondate.replace(/\//g, "-");
            jsondate = jsondate.replace(" ", "T");
            jsondate += tail;
            datetime = new Date(jsondate);
        }
        if (!format) format = "yyyy.MM.dd";
        return datetime.Format(format);
    },
    //获取JSON格式日期的时间戳
    getTimeStamp: function (jsondate) {
        var datetime = "";
        if (!jsondate) {
            return "";
        }
        jsondate = jsondate + "";
        if (/^\/Date[(].+[)]\/$/.test(jsondate)) {
            jsondate = jsondate.replace("/Date(", "").replace(")/", "");
            if (jsondate.indexOf("+") > -1) {
                jsondate = jsondate.substring(0, jsondate.indexOf("+"));
            }
            else if (jsondate.indexOf("-") > -1) {
                jsondate = jsondate.substring(0, jsondate.indexOf("-"));
            }
            datetime = new Date(parseInt(jsondate, 10));
        } else {
            //时间戳
            if (/^\d{13}$/.test(jsondate)) {
                return jsondate;
            } else {
                //常规时间
                //如果不存在毫秒
                if (jsondate.indexOf(".") < 0) {
                    jsondate += ".0";
                }
                jsondate = jsondate.replace(/\//g, "-");
                jsondate = jsondate.replace(" ", "T");
                jsondate += "+08:00";
                datetime = new Date(jsondate);
            }
        }
        return datetime.getTime();
    },
    getTimeAgo: function (jsondate) { //dateTimeStamp是一个时间毫秒，注意时间戳是秒的形式，在这个毫秒的基础上除以1000，就是十位数的时间戳。13位数的都是时间毫秒。
        var dateTimeStamp = this.getTimeStamp(jsondate);
        var minute = 1000 * 60;      //把分，时，天，周，半个月，一个月用毫秒表示
        var hour = minute * 60;
        var day = hour * 24;
        var week = day * 7;
        var halfamonth = day * 15;
        var month = day * 30;
        var now = new Date().getTime();   //获取当前时间毫秒
        var diffValue = now - dateTimeStamp;//时间差

        if (diffValue < 0) {
            return;
        }
        var minC = diffValue / minute;  //计算时间差的分，时，天，周，月
        var hourC = diffValue / hour;
        var dayC = diffValue / day;
        var weekC = diffValue / week;
        var monthC = diffValue / month;
        if (monthC >= 1 && monthC <= 3) {
            result = " " + parseInt(monthC) + "月前"
        } else if (weekC >= 1 && weekC <= 3) {
            result = " " + parseInt(weekC) + "周前"
        } else if (dayC >= 1 && dayC <= 6) {
            result = " " + parseInt(dayC) + "天前"
        } else if (hourC >= 1 && hourC <= 23) {
            result = " " + parseInt(hourC) + "小时前"
        } else if (minC >= 1 && minC <= 59) {
            result = " " + parseInt(minC) + "分钟前"
        } else if (diffValue >= 0 && diffValue <= minute) {
            result = "刚刚"
        } else {
            var datetime = new Date();
            datetime.setTime(dateTimeStamp);
            var Nyear = datetime.getFullYear();
            var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
            var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
            var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
            var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
            var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
            result = Nyear + "-" + Nmonth + "-" + Ndate
        }
        return result;
    },
    //编码
    zip: function (jsonObj) {
        if (!jsonObj) return jsonObj;
        if (jsonObj instanceof String) {
            return encodeURIComponent(jsonObj);
        } else {
            return encodeURIComponent(JSON.stringify(jsonObj));
        }
    },
    //解码
    unzip: function (jsonStr) {
        if (!jsonStr) return jsonStr;
        return eval("(" + decodeURIComponent(jsonStr) + ")");
    },
    //格式化图片地址
    formatImgUrl: function (url) {
        return $.formatImgUrl(url);
    },
    //格式数字，千分号显示
    formatNumber: function (num) {
        var decimalPart = '';
        num = num.toString();
        if (num.indexOf('.') != -1) {
            decimalPart = '.' + num.split('.')[1];
            num = parseInt(num.split('.')[0]);
        }
        var array = num.toString().split('');
        var index = -3;
        while (array.length + index > 0) {
            array.splice(index, 0, ',');
            index -= 4;
        }
        return array.join('') + decimalPart;
    }
};

//金钱处理专用
if (!String.prototype.formatMoney) {
    String.prototype.formatMoney = function () {
        var that = "";
        if (((this + "").match(/\.\d+/) + "").length > 15) {
            //一看就是精度不准
            that = parseFloat(this).toFixed(2);
        } else {
            that = this;
        }
        var money = 0;
        //取两位小数
        var match = that.match(/\d{1,}\.\d{2}/, "");
        if (match && match.length > 0) {
            money = match[0];
        } else {
            money = that;
        }
        return parseFloat(money).toFixed(2);
    };

    Number.prototype.formatMoney = function () {
        return (this + "").formatMoney();
    };
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy.MM.dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    for (var time in o) {
        if (isNaN(o[time])) {
            return "";
        }
    }
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
//移除历史中的某页
//pathname不输入或者输入null，则代表删除当前页
//isOnce，默认为false，如果为true则代表删除所有页面名称相同的历史页面，false则只删除最近的相同页面
Array.prototype.remove = function (pathname, isOnce) {
    if (!pathname) {
        pathname = document.location.pathname.toLowerCase();
    }
    var wHistory = gp.history;
    for (var j = wHistory.length - 1; j >= 0; j--) {
        var page = wHistory[j];
        if (page.pathname.toLowerCase() == pathname.toLowerCase()) {
            wHistory.splice(j, 1);
            if (isOnce) {
                break;
            }
        }
    }
    gp.cache.set("wHistory", wHistory);
};

//清除除了自己页面的所有历史记录，仅保留自己页面
Array.prototype.clear = function () {
    var wHistory = gp.history;
    if (wHistory.length > 0) {
        wHistory.splice(0, wHistory.length - 1);
    }
    gp.history = wHistory;
    gp.cache.set("wHistory", wHistory);
};

//添加页面进入历史记录
Array.prototype.add = function (pathname) {
    var wHistory = null;
    if (gp.cache.get("wHistory")) {
        wHistory = JSON.parse(gp.cache.get("wHistory"));
    } else {
        wHistory = [];
    }
    if (wHistory.length >= 15) {
        var wNewArray = [];
        for (var i = 0; i < 5; i++) {
            wNewArray.push(wHistory.pop());
        }
        wHistory = wNewArray;
    }

    //如果是不存页面名称，则取当前页面名称，否则取传递过来的页面名称
    if (!pathname) {
        //相同页面则跳过
        if (wHistory.length > 0) {
            if (wHistory[wHistory.length - 1].href.toLowerCase() == window.location.href.toLowerCase()) {
                return;
            }
        }
        wHistory.push(JSON.parse(JSON.stringify({
            href: window.location.href,
            request: window.location.request,
            pathname: window.location.pathname.toLowerCase()
        })));
    } else {
        wHistory.push({
            href: pathname,
            request: pathname,
            pagename: pathname
        });
    }
    gp.cache.set("wHistory", wHistory);
    gp.history = wHistory;
};